/**
 * 基于web-storage-cache,加前缀
 */
import WebStorageCache from 'web-storage-cache'

type CacheType = 'localStorage' | 'sessionStorage'

class PrefixWebStorageCache extends WebStorageCache {
  private readonly prefix: string
  private readonly cacheType: CacheType

  constructor(type: CacheType, prefix: string) {
    super({ storage: type })
    this.prefix = prefix + ':'
    this.cacheType = type
  }

  set(key: string, value: any, options?: any) {
    super.set(`${this.prefix}${key}`, value, options)
  }

  get(key: string): any {
    return super.get(`${this.prefix}${key}`)
  }

  delete(key: string) {
    super.delete(`${this.prefix}${key}`)
  }

  deleteAllExpires() {
    throw new Error('deleteAllExpires该方法不可用')
  }

  clear() {
    const storage = this.cacheType === 'localStorage' ? localStorage : sessionStorage
    const allKeys = Object.keys(storage)
    for (let i = 0; i < allKeys.length; i++) {
      if (allKeys[i].startsWith(this.prefix)) {
        storage.removeItem(allKeys[i])
      }
    }
  }

  touch(key: string, exp: number) {
    super.touch(`${this.prefix}${key}`, exp)
  }

  add(key: string, value: any, options?: any) {
    super.add(`${this.prefix}${key}`, value, options)
  }

  replace(key: string, value: any, options?: any) {
    super.replace(`${this.prefix}${key}`, value, options)
  }
}

export { CacheType }
export default PrefixWebStorageCache
